import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Compress.java - This class takes in an .xml file, and GZIPs the xml to save the document
 *   
 * @author Andrew Gifford
 */
public class Compress {
	
	public static int bufferSize = 8192;
	/**
	 * Takes in an xml file, and outputs a zipped .xml file
	 * 
	 * @param fileName the filename of the file to be compressed
	 * @return VOID
	 */
	public static void compressFile(String fileName){
	
		GZIPOutputStream zOut = null;
		try {
			FileOutputStream out = new FileOutputStream(fileName);
			zOut = new GZIPOutputStream (out);
		}
		catch ( IOException e) {
			System.out.println(" Couldn't create " + fileName + ".");
			return;
		}
		
		byte [] buffer = new byte [ bufferSize ];
		// compress the file
		try {
			FileInputStream in = new FileInputStream ("spreadsheet.temp");
			int length;
			while ((length = in.read(buffer, 0, bufferSize)) != -1){
				zOut.write (buffer , 0, length );
			}
			in.close();
		}
		catch ( IOException e) {System.out.println(" Couldn't compress " + fileName + ".");}
		try { 
			zOut.close(); 
		}
		catch (IOException e) {System.out.println("Close File Error.");}
	}
	/**
	 * Takes in a zipped file, and outputs an xml to be read into the spreadsheet
	 * 
	 * @param fileName the filename of the file to be decompressed
	 * @return VOID
	 */
	public static void decompressFile(String fileName){
		

		GZIPInputStream zIn ;
		try {
			FileInputStream in = new FileInputStream(fileName);
			zIn = new GZIPInputStream (in);
		}
		catch ( IOException e) {
			System.out.println(" Couldn't open " + fileName + ".");
			return ;
		}
		byte [] buffer = new byte [bufferSize];
		
		// decompress the file
		try {
			FileOutputStream out = new FileOutputStream ("spreadsheet.temp");

			int length;
			while (( length = zIn.read(buffer, 0, bufferSize )) != -1){
				out.write(buffer, 0, length );
			}
			out.close();
		}
		catch ( IOException e) {System.out.println(" Couldn't decompress " + fileName + ".");}
		try {
			zIn.close();
		}
		catch (IOException e) {System.out.println("Close File Error");}
	}
	/**
	 * Takes in a file name, and deletes that file from the directory
	 * 
	 * @param fileName the filename of the file to be deleted
	 * @return VOID
	 */
	public static void deleteFile(String fileName){
		File f = new File(fileName);
		
		if(! f.delete()){
			System.out.println("Delete Not Successful");
		}
	}	
}
